var express = require('express'); //express.js export.express ={}
var bodyParser = require('body-parser')
const fs = require('fs');
var FILE = 'data.json';  
var server = express()   
server.use(bodyParser.urlencoded({ extended: false })) 
server.use(bodyParser.json())
var app = {
    args(req, res){
     if(!req.query.table) return res.send('need table name');
     var tmp = Object.assign(req.parmas||{},req.query,req.body||{})
     delete tmp['table'];
     return tmp;
    },
    read(){ return JSON.parse(fs.readFileSync(FILE));},
    write(obj){ fs.writeFileSync(FILE,JSON.stringify(obj));},
    create(req, res){
     var arg = app.args(req, res);        
     var tables = app.read()
     var table = tables[req.query.table]|| [];  
     table.push(Object.assign(arg,{id:Date.now()}));
     tables[req.query.table] = table;
     app.write(tables)
     res.send(arg);
    },
    update(req, res){
     var arg = app.args(req, res);        
     var tables = app.read(),lines=0;
     var table = tables[req.query.table]|| [];  
     table.map(e=>{
        if(e.id === arg.id) {  lines ++;  return Object.assign(e,arg) }
        return e; 
     })
     tables[req.query.table] = table;
     app.write(tables)
     res.send({ lines });
    },
    delete(req, res){
     var arg = app.args(req, res);        
     var tables = app.read(),lines=0;
     var table = tables[req.query.table]|| [];  
     lines = table.length;
     table = table.filter(({ id })=> id !== arg.id );
     lines = lines - table.length;
     tables[req.query.table] = table;
     app.write(tables)
     res.send({ lines });
    },
    search(req, res){
     var arg = app.args(req, res);        
     var tables = app.read();
     var table = tables[req.query.table]|| [];  
     res.send(table.filter(({ id })=> id === arg.id ))
    },
    searchs(req, res){
     var arg = app.args(req, res);        
     var tables = app.read();
     var table = tables[req.query.table]|| [];  
     for(var key in arg.where.eq) table.filter((e)=> e[key] === arg.where.eq[key] );
     for(var key in arg.where.like) table.filter((e)=> e[key].indexOf(arg.where.eq[key]) > -1);
     res.send(table.slice(arg.skip || 0 , (arg.skip + arg.limit)|| 100 ));
    },
} 
server.post('/create', app.create);
server.post('/update', app.update);
server.post('/delete', app.delete);
server.post('/search', app.search);
server.post('/searchs', app.searchs);
server.listen(1234, () => {  app.write({});});